package com.chengqj.template;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @program: pattern
 * @description: jdbc的链接抽象类
 * @author: chengqj
 * @create: 2018-07-30 18:59
 **/
public abstract class AbstractJdbcTemplate {
    public List<?> executeQuery(String sql) {
        //1、获取连接
        Connection conn = getConnection();
        //2、创建语句集
        PreparedStatement pstmt = createPreparedStatement(conn, sql);
        //3、执行语句集，并且获得结果集
        ResultSet rs = execute(pstmt);
        //4、解析语句集
        List<?> result = parseResultSet(rs);
        //5、各个服务关闭
        close(conn, pstmt, rs);
        return null;
    }

    protected abstract Connection getConnection();

    protected abstract List<?> parseResultSet(ResultSet rs);

    protected PreparedStatement createPreparedStatement(Connection conn, String sql) {
        try {
            return conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected ResultSet execute(PreparedStatement pstmt) {
        try {
            return pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
